<script setup lang="ts">
import { ref, useTemplateRef } from 'vue'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import VideoWrap from '../../components/video-wrap.vue'
import { useGsapContext } from '@/hooks'
import { useScrollGroup } from '@/hooks/reno14-pro.ts'
import { useIntersectionObserver } from '@vueuse/core'

const { scrollGroup } = useScrollGroup()

const containerRef = useTemplateRef<HTMLDivElement | null>('containerRef')
const videoRef = useTemplateRef<HTMLVideoElement | null>('videoRef')
const playing = ref(false)
useIntersectionObserver(videoRef, ([{ isIntersecting }]) => {
  if (!isIntersecting) {
    const video = videoRef.value
    if (video) {
      video.pause()
      video.currentTime = 0
    }
  }
})

useGsapContext(() => {
  if (!containerRef.value || !videoRef.value) {
    return
  }

  ScrollTrigger.create({
    trigger: containerRef.value,
    start: 'top center',
    end: 'bottom center',
    onToggle: async (self) => {
      const video = videoRef.value

      if (self.isActive && video) {
        await video.play().catch()
      }
    },
    invalidateOnRefresh: true,
    ...scrollGroup,
  })
})
</script>

<template>
  <div
    ref="containerRef"
    class="mt-[0.375rem] bg-[#201f1c] rounded-sm px-[5.6vw] py-[6.56vw] md:p-[1.5rem] md:grid md:grid-cols-[35.45vw_1fr] md:gap-x-[3rem] lg:grid-cols-[36%_1fr] lg:px-[clamp(1.375rem,0.125rem+1.9531vw,2rem)] lg:py-[clamp(2rem,0rem+3.125vw,3rem)]"
  >
    <div class="md:col-start-2 md:row-start-1 md:grid items-center content-center">
      <div class="text-3xl leading-[1.26] lg:text-[clamp(2rem,0rem+3.125vw,3rem)]">
        <p>闪光实况照片</p>
        <p>
          闪光拍实况 <br class="md:hidden" />
          更有生命力
        </p>
      </div>
      <div class="mt-[1.375rem] md:mt-[1rem]">
        <p class="text-base lg:text-[clamp(0.75rem,0rem+1.1719vw,1.125rem)]">
          超亮智能闪光灯，闪亮登场。同档首创三灯方案，广角和长焦全覆盖。灯光一闪，Get CCD
          同款氛围感。
        </p>
      </div>
    </div>

    <VideoWrap class="max-md:mt-[1.75rem] md:col-start-1 md:row-start-1" :playing>
      <video
        ref="videoRef"
        class="w-full h-full object-cover aspect-[3/4] lg:aspect-[112/149]"
        muted
        @play="playing = true"
        @ended="playing = false"
        src="@/views/product/reno14-pro/image/4/videos-live-2-c1-1-pc.mp4"
      ></video>
    </VideoWrap>
  </div>
</template>
